<template>
    <view>
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
        <wlk-navbar title="编辑资料" navbarType='3'></wlk-navbar>
        <view class="info-content br08">
            <u--form
                    labelPosition="left"
                    :model="form"
                    :rules="rules"
                    ref="uForm"
            >
                <!-- #ifndef MP-WEIXIN -->
                <view class="cell u-flex" @click="upAvatar">
                    <view class="title u-flex-m">头像</view>
                    <u-avatar :src="form.userInfo.avatar"></u-avatar>
                    <u-icon name="arrow-right"></u-icon>
                </view>
                <!-- #endif -->
                <!-- #ifdef MP-WEIXIN -->
                    <button class="cell u-flex" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                        <view class="title u-flex-m">头像</view>
                        <u-avatar :src="form.userInfo.avatar"></u-avatar>
                        <u-icon name="arrow-right"></u-icon>
                    </button>
                <!-- #endif -->
                <u-form-item
                        labelWidth="70"
                        label="用户名"
                        prop="userInfo.username"
                        borderBottom
                        ref="item1"
                >
                    <u--input
                            :customStyle="{
                                 padding:'18rpx 0'
                            }"
                            v-model="form.userInfo.username"
                            clearable
                            border="none"
                    ></u--input>
                </u-form-item>
                <u-form-item
                        labelWidth="70"
                        label="昵称"
                        prop="userInfo.nickname"
                        borderBottom
                        ref="item1"
                >
                    <!-- #ifndef MP-WEIXIN -->
                    <u--input
                            :customStyle="{
                                 padding:'18rpx 0'
                            }"
                            v-model="form.userInfo.nickname"
                            clearable
                            border="none"
                    ></u--input>
                    <!-- #endif -->
                    <!-- #ifdef MP-WEIXIN -->
                    <u--input
                            :customStyle="{
                                 padding:'18rpx 0'
                            }"
                            v-model="form.userInfo.nickname"
                            clearable
                            type="nickname"
                            border="none"
                            @blur="onBlur"
                    ></u--input>
                    <!-- #endif -->
                </u-form-item>
                <u-form-item
                        labelWidth="70"
                        label="性别"
                        prop="userInfo.gender"
                        borderBottom
                        @click="showSex = true"
                        ref="item1"
                >
                    <u--input
                            :customStyle="{
                                padding:'18rpx 0'
                            }"
                            v-model="form.userInfo.gender"
                            readonly
                            placeholder="请选择性别"
                            border="none"
                    ></u--input>
                    <u-icon
                            slot="right"
                            name="arrow-right"
                    ></u-icon>
                </u-form-item>
                <u-form-item
                        labelWidth="70"
                        label="生日"
                        prop="userInfo.birthday"
                        @click="showBirthday = true"
                        ref="item1"
                >
                    <u--input
                            :customStyle="{
                               padding:'18rpx 0'
                            }"
                            v-model="form.userInfo.birthday"
                            readonly
                            placeholder="请选择生日"
                            border="none"
                    ></u--input>
                    <u-icon
                            slot="right"
                            name="arrow-right"
                    ></u-icon>
                </u-form-item>
            </u--form>
        </view>
        <view class="bind-info pd30" v-if="platform !== 'H5'">
            <view class="head-title mb30 mt20 bold">第三方账号</view>
            <!-- #ifdef MP-WEIXIN -->
            <view class="wlkflex justify-between bgw pd30">
                <view class="title">微信账号</view>
                <view class="wlkflex">
                    <block  v-if="!$u.test.isEmpty(userInfo.otherAuth)">
                        <u-avatar size="30" :src="userInfo.otherAuth.headimgurl"></u-avatar>
                        <view class="ml10 mr10 nickname">
                            {{userInfo.otherAuth.nickname}}
                        </view>
                        <u-button :customStyle="{
			            height:'50rpx',
			            width:'auto',
			            padding:'0 15rpx'
                        }" :color="themeColor"  shape="circle" type="primary" disabled text="已绑定"></u-button>
                    </block>
                    <u-button  :customStyle="{
			            height:'50rpx',
			            width:'auto',
			            padding:'0 15rpx'
                        }" v-else   @click="wxBind" :color="themeColor" shape="circle" type="primary" text="绑定"></u-button>
                </view>
            </view>
            <!-- #endif -->
            <!-- #ifdef H5 -->
            <view v-if="platform === 'wxOfficialAccount'" class="wlkflex justify-between bgw pd30">
                <view class="title">微信账号</view>
                <view class="wlkflex">
                    <block  v-if="!$u.test.isEmpty(userInfo.otherAuth)">
                        <u-avatar size="30" :src="userInfo.otherAuth.headimgurl"></u-avatar>
                        <view class="ml10 mr10 nickname">
                            {{userInfo.otherAuth.nickname}}
                        </view>
                        <u-button :customStyle="{
			            height:'50rpx',
			            width:'auto',
			            padding:'0 15rpx'
                        }" :color="themeColor"  shape="circle" type="primary" disabled text="已绑定"></u-button>
                    </block>
                    <u-button  :customStyle="{
			            height:'50rpx',
			            width:'auto',
			            padding:'0 15rpx'
                        }" v-else   @click="wxBind" :color="themeColor" shape="circle" type="primary" text="绑定"></u-button>
                </view>
            </view>
            <!-- #endif -->
        </view>
        <u-picker :show="showSex" :columns="columns" keyName="label" :defaultIndex="defaultIndex" closeOnClickOverlay @close="showSex = false" @cancel="showSex = false" @confirm="confirm" :confirmColor="themeColor"></u-picker>
        <u-datetime-picker
                ref="datetimePicker"
                :show="showBirthday"
                v-model="birthday"
                :minDate="-2209017943000"
                :maxDate="4133865600000"
                closeOnClickOverlay @close="showBirthday = false" @cancel="showBirthday = false" @confirm="dayConfirm"
                mode="date"
        ></u-datetime-picker>
        <view class="wlk-fixed-btn">
            <u-button :customStyle="{
                    fontWeight: 'bold',
			        borderRadius:'8px',
			          width:'92%'
                }" :color="themeColor" size="large" @click="submit" text="保存"></u-button>
        </view>
    </view>
</template>

<script>
    var _self;
    import { mapActions, mapGetters } from 'vuex';
    import platform from '@/wlkutils/platform';
    import courtConfig from "@/base";
    export default {
        computed: {
            ...mapGetters(['userInfo','themeColor','isLogin'])
        },
        data() {
            return {
                showSex: false,
                showBirthday: false,
                defaultIndex:[],
                birthday:'',
                form: {
                    userInfo: {
                        avatar: '',
                        nickname: '',
                        username: '',
                        gender: '',
                        birthday: '',
                    },
                },
                columns: [
                    [
                        {
                            label: '女',
                            value: 0
                        },
                        {
                            label: '男',
                            value:1,
                        }
                    ]
                ],
                rules: {
                    'userInfo.username': {
                        type: 'string',
                        required: true,
                        message: '请填写用户名',
                        trigger: ['blur', 'change']
                    },
                    'userInfo.nickname': {
                        type: 'string',
                        required: true,
                        message: '请填写昵称',
                        trigger: ['blur', 'change']
                    },
                    'userInfo.gender': {
                        type: 'string',
                        max: 1,
                        required: true,
                        message: '请选择性别',
                        trigger: ['blur', 'change']
                    },
                    'userInfo.birthday': {
                        type: 'string',
                        required: true,
                        message: '请选择生日',
                        trigger: ['change']
                    },
                },
                fileUrl:'',
                platform:platform.get(),
            };
        },
        onLoad(options) {
            _self = this;
        },
        onShow() {
            this.form.userInfo.username = this.userInfo.username;
            this.form.userInfo.nickname = this.userInfo.nickname;
            this.form.userInfo.birthday = this.userInfo.birthday;
            this.birthday = this.userInfo.birthday;
            this.defaultIndex[0] = this.userInfo.gender;
            this.form.userInfo.gender = this.columns[0][this.userInfo.gender].label;
            if (!uni.$u.test.isEmpty(this.userInfo.avatar)) {
                this.form.userInfo.avatar = this.userInfo.avatar;
            }
        },
        onReady() {
            this.$refs.uForm.setRules(this.rules);
        },
        methods: {
            ...mapActions(["getUserInfo"]),
            onBlur(e){
                this.form.userInfo.nickname = e
            },
            // 修改头像
            upAvatar(){
                uni.chooseImage({
                    count:1,
                    success:(res)=>{
                        const tempFilePaths = res.tempFilePaths;
                        uni.$u.http.upload('common/upload', {
                            filePath:tempFilePaths[0],
                            name:'file',
                        }).then(res => {
                            _self.form.userInfo.avatar = res.data.url;
                            _self.fileUrl = res.data.fileUrl;
                        }).catch(err => {
                            _self.$u.toast('图片格式不正确');
                        })
                    }
                })
            },
            onChooseAvatar(e){
                uni.$u.http.upload('common/upload', {
                    filePath: e.detail.avatarUrl,
                    name: 'file',
                }).then(res => {
                    _self.form.userInfo.avatar = res.data.url;
                    _self.fileUrl = res.data.fileUrl;
                }).catch(err => {
                    _self.$u.toast('图片格式不正确');
                })
            },
            dayConfirm(e){
                this.form.userInfo.birthday =  uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
                setTimeout(function () {
                    this.birthday =  uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
                },200);
                this.showBirthday = false;
            },
            confirm(e) {
                this.form.userInfo.gender = this.columns[0][e.indexs[0]].label;
                this.defaultIndex[0] = e.indexs[0];
                this.showSex = false;
            },
            submit() {
                this.$refs.uForm.validate().then(res => {
                    var data = JSON.parse(JSON.stringify(this.form.userInfo));
                    if (!uni.$u.test.isEmpty(this.fileUrl)) {
                        data.avatar = this.fileUrl;
                    }else{
                        data.avatar = '';
                    }
                    data.gender = this.columns[0][this.defaultIndex[0]].value;
                    uni.$u.http.post('user/profile', data).then(res => {
                        _self.getUserInfo();
                        uni.$u.toast(res.msg);
                    }).catch(res => {

                    })
                }).catch(errors => {
                })
            },
            wxBind(){
                if(this.isLogin){
                    //  #ifdef MP-WEIXIN
                    this.$store.commit('setShowWxLogin',true)
                    this.getUserInfo();
                    //  #endif
                    //  #ifdef H5
                    if(this.platform == 'wxOfficialAccount'){
                        let host = platform.host();
                        let curPage = getCurrentPages();
                        let params = curPage[curPage.length - 1].options??{}; //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}
                        let payloadObject = {
                            host: host,
                            event: 'bind',
                            agent_id:uni.$u.test.isEmpty(uni.getStorageSync('agent_id'))?0:null,
                            local: uni.$u.page()+uni.$u.queryParams(params),
                        };
                        let payload = encodeURIComponent(JSON.stringify(payloadObject));
                        uni.$u.http.post('wechat/codeUrl',
                            {
                                url: courtConfig.apiUrl + '/wechat/oaLogin',
                                payload: payload,
                            }).then((res) => {
                            location.href = res.data;
                        })
                    }
                    //  #endif

                }
            }
        },

    };
</script>

<style lang="scss">
    .info-content{
        width: 92%;
        padding: 0 30rpx;
        background-color: #FFFFFF;
        margin: 40rpx auto 0 auto;
        box-shadow: 0 2px 4px rgba(0,0,0,.02);
    }
    .u-cell{
        padding:0;
    }
    .u-flex{
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .u-flex-m {
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        overflow: hidden
    }
    .u-form-item{

    }
    .cell {
        position: relative;
        padding: 24rpx 0;
        border-bottom: 1rpx solid #eee;
        .title {
            font-size: $font-base;
            color: #333;
            text-align: left;
        }
        .text{

            color: #888;
        }
        .itemButton{
            border-radius: 0;
            text-align: left;
            opacity: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
        }
        &:last-child{
            border-bottom: none;
        }
        .avatar{
            width: 80rpx;
            height: 80rpx;
            border-radius: 40rpx;
            margin-right: 10rpx;
        }
    }
    .bind-info{
        .title{
            font-size: $font-lt;
        }
        .head-title{
            font-size: $font-lt;
        }
        .nickname{
            font-size: $font-base;
        }
    }
    .wlk-fixed-btn{
        box-shadow: 0px -5px 5px rgba(0, 0, 0, 0);
        background-color: transparent;
    }
</style>
